package com.mentalhealthplatform.schoolV1.service;

import com.mentalhealthplatform.appModels.Assessment;
import com.mentalhealthplatform.appModels.Student;
import com.mentalhealthplatform.schoolV1.dto.AssessmentDTO;
import com.mentalhealthplatform.schoolV1.repository.AssessmentRepositoryV1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AssessmentServiceV1 {

    @Autowired
    private AssessmentRepositoryV1 assessmentRepositoryV1;

    // 根据过滤条件获取评估数据并返回DTO
    public List<AssessmentDTO> getAssessments(String dateRange, String evaluation) {
        LocalDateTime startDate = null;
        LocalDateTime endDate = LocalDateTime.now();

        // 设置日期范围
        if ("last7days".equals(dateRange)) {
            startDate = endDate.minusDays(7);
        } else if ("last30days".equals(dateRange)) {
            startDate = endDate.minusDays(30);
        } else if ("thisMonth".equals(dateRange)) {
            startDate = LocalDateTime.of(endDate.getYear(), endDate.getMonth(), 1, 0, 0, 0, 0);
        } else if ("lastMonth".equals(dateRange)) {
            startDate = LocalDateTime.of(endDate.getYear(), endDate.getMonth().minus(1), 1, 0, 0, 0, 0);
            endDate = LocalDateTime.of(endDate.getYear(), endDate.getMonth(), 1, 0, 0, 0, 0);
        }

        // 查询数据
        List<Assessment> assessments = assessmentRepositoryV1.findByFilters(startDate, endDate, evaluation);

        return assessments.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }


    private AssessmentDTO convertToDTO(Assessment assessment) {
        Student student = assessment.getStudent();

        // 如果学生信息为空，只返回评估信息
        if (student == null) {
            return new AssessmentDTO(
                    assessment.getId(),
                    assessment.getScore(),
                    assessment.getEvaluation(),
                    assessment.getSubmittedTime(),
                    assessment.getStudentId()
            );
        }

        // 如果学生信息不为空，返回评估信息和学生详细信息
        return new AssessmentDTO(
                assessment.getId(),
                assessment.getScore(),
                assessment.getEvaluation(),
                assessment.getSubmittedTime(),
                student.getName(),
                student.getCollege(),
                student.getMajor(),
                student.getGender(),
                student.getGrade(),
                student.getId()
        );
    }

}
